import React from 'react';
import {connect} from 'dva/index';
import {Button, Col, DatePicker, Form, Input, Radio, Row, Table} from 'antd';
import Constants from '../../utils/Constants';
import RightConstants from '../../utils/RightConstants';
import RightBox from '../../components/common/rightBox';
import PortSelect from '../../components/common/portSelect';
import RoleSelect from '../../components/common/roleSelect';
import OrderDetail from '../../components/logisticsOrder/orderDetail';

const FormItem = Form.Item;
const R = require("ramda");
const { RangePicker } = DatePicker;
const RadioGroup = Radio.Group;

const order = Form.create()(class Order extends React.Component {
    constructor(props) {
        super(props);
    }

    componentDidMount() {
        this.props.dispatch({ type: 'order/getListForPage', payload: { page: Constants.DEFAULT_PAGE } });
    }

    handleOpen = (record, disabled, cstEdit) => {
        this.fetchDetail(record.id, record.orderId);
        this.orderDetail.handleOpen(record.id, record.orderId, disabled, cstEdit, null, true, true);
    }

    fetchDetail = (id, orderId) => {
        this.props.dispatch({ type: 'berthingCompany/getAllBerthingCompanys' }); //查询船公司
        this.props.dispatch({ type: 'airCompany/getAllAirCompanys' }); //查询航空公司

        this.props.dispatch({ type: 'supplier/getDecSupplierList' });  //查询报关供应商List
        this.props.dispatch({ type: 'supplier/getTraSupplierList' });  //查询拖车供应商List
        this.props.dispatch({ type: 'supplier/getInsSupplierList' });  //查询保险供应商List
        this.props.dispatch({ type: 'supplier/getStoSupplierList' });  //查询仓内装供应商List
        this.props.dispatch({ type: 'supplier/getInspectionSupplierList' });  //查询商检供应商List
        this.props.dispatch({ type: 'supplier/getCoSupplierList' });  //查询产地证供应商List
        this.props.dispatch({
            type: 'order/getById',
            payload: {
                receiptId: id
            }
        });
        this.props.dispatch({ //费用确认审批历史
            type: 'approvalHistory/getListForPage',
            payload: {
                businessTypes: [Constants.BUSINESSTYPE.CHARGECONFIRM],
                key: Constants.BUSINESSTYPE.CHARGECONFIRM,
                entityId: orderId,
                page: Constants.DEFAULT_PAGE
            }
        });
        this.props.dispatch({ //费用变更新增审批历史
            type: 'approvalHistory/getListForPage',
            payload: {
                businessTypes: [Constants.BUSINESSTYPE.CHARGE_ADD_PAY, Constants.BUSINESSTYPE.CHARGE_ADD_CLAIM],
                key: Constants.BUSINESSTYPE.CHARGE_ADD,
                entityId: orderId,
                page: Constants.DEFAULT_PAGE
            }
        });
        this.props.dispatch({ //费用变更修改审批历史
            type: 'approvalHistory/getChargeUpdateForPage',
            payload: {
                businessTypes: [Constants.BUSINESSTYPE.CHARGE_UPDATE_PAY, Constants.BUSINESSTYPE.CHARGE_UPDATE_CLAIM],
                key: Constants.BUSINESSTYPE.CHARGE_UPDATE,
                orderId: orderId,
                page: Constants.DEFAULT_PAGE
            }
        });
    }

    handleSearch = flag => {
        let values = this.props.form.getFieldsValue();
        values.drBeginTime = R.isNil(values.deliveryTime) || R.isEmpty(values.deliveryTime) ? null : values.deliveryTime[0].format(Constants.DATEFORMAT);
        values.drEndTime = R.isNil(values.deliveryTime) || R.isEmpty(values.deliveryTime) ? null : values.deliveryTime[1].format(Constants.DATEFORMAT);
        values.deliveryTime = undefined;
        let newPage = this.props.order.page;
        if (flag) newPage.page = 1;
        this.props.dispatch({
            type: 'order/getListForPage',
            payload: {
                ...values,  
                page: newPage
            }
        });
    };

    columns = [
        { title: '提交时间', dataIndex: 'drTime', key: 'drTime' },
        { title: '服务类型', key: 'serviceItems',
            render: record =>{
                return <span>{record.shipping ? "海运" : null}
                             {record.airFreight ? "空运" : null}
                             {record.portService ? (record.shipping || record.airFreight ? "/港前" : "港前") : null}
                             {record.vasService ? (record.shipping || record.airFreight || record.portService ? "/增值" : "增值") : null}
                        </span>
            }
        },
        { title: '订单号', dataIndex: 'orderno', key: 'orderno' },
        { title: '客户名称', dataIndex: 'companyName', key: 'companyName' },
        { title: 'SO', dataIndex: 'soNo', key: 'soNo' },
        { title: '柜号', dataIndex: 'cntrNo', key: 'cntrNo' },
        {
            title: '起运港',
            render: record => {
                return <span>
                    <div>{record.loadingPortNameEn}</div>
                    <div>({record.loadingPortName})</div>
                </span>
            }
        },
        {
            title: '目的港',
            render: record => {
                return <span>
                    <div>{record.destinationPortNameEn}</div>
                    <div>({record.destinationPortName})</div>
                </span>
            }
        },
        { title: '业务员', dataIndex: 'creatorName', key: 'creatorName' },
        {
            title: '跟单进展', render(record) {
                if (record.orderStatus == '2') {
                    return '接单';
                } else if (record.orderStatus == '3') {
                    return '拖车';
                } else if (record.orderStatus == '4') {
                    return '报关中';
                } else if (record.orderStatus == '5') {
                    return '报关放行';
                } else if (record.orderStatus == '6') {
                    return '补料';
                } else if (record.orderStatus == '7') {
                    return '未收款';
                } else if (record.orderStatus == '8') {
                    return '已收款';
                } else if (record.orderStatus == '9') {
                    return '放单';
                } else if(record.orderStatus == '10'){
                    return '上船'
                } else if(record.orderStatus == '11'){
                    return '订舱中'
                }
            }
        },
        {
            title: '操作',
            render: (record) => {
                let operatorLink = <RightBox resource={RightConstants.ORDER.ORDER_OPERATOR}><a href="#" onClick={this.handleOpen.bind(this, record, false, true)}>操作跟单</a></RightBox>
                return <span>{operatorLink}</span>
            }
        }
    ];

    render() {
        let formItemLayout = { labelCol: { span: 8 }, wrapperCol: { span: 16 } };
        const { getFieldDecorator } = this.props.form;
        let values = this.props.form.getFieldsValue();
        values.drBeginTime = R.isNil(values.deliveryTime) || R.isEmpty(values.deliveryTime) ? null : values.deliveryTime[0].format(Constants.DATEFORMAT);
        values.drEndTime = R.isNil(values.deliveryTime) || R.isEmpty(values.deliveryTime) ? null : values.deliveryTime[1].format(Constants.DATEFORMAT);
        values.deliveryTime = undefined;
        let pagination = {
            showTotal: total => `共 ${total} 条数据`,
            pageSize: this.props.order.page.size,
            current: this.props.order.page.page,
            total: this.props.order.page.totalRow,
            showSizeChanger: true,
            onShowSizeChange: (current, size) => {
                let newPage = this.props.order.page;
                newPage.size = size;
                newPage.page = 1;
                this.props.dispatch({
                    type: 'order/getListForPage',
                    payload: {
                        ...values,
                        page: newPage
                    }
                });
            },
            onChange: (pageNumber, pageSize) => {
                let newPage = this.props.order.page;
                newPage.page = pageNumber;
                this.props.dispatch({
                    type: 'order/getListForPage',
                    payload: {
                        ...values,
                        page: newPage
                    }
                });
            }
        }

        return (
            <div>
                <Row>
                    <Col span={8}>
                        <FormItem {...formItemLayout} label={'订单/SO号'}>
                            {getFieldDecorator('orderNo')
                                (
                                <Input maxLength="20" placeholder="可根据订单编号或SO号搜索" style={{ width: '100%' }} />
                                )
                            }
                        </FormItem>
                    </Col>
                    <Col span={8}>
                        <FormItem {...formItemLayout} label={'柜号/封号'}>
                            {getFieldDecorator('cntrNo')
                                (
                                <Input maxLength="20" placeholder="可根据柜号或封号搜索" style={{ width: '100%' }} />
                                )}
                        </FormItem>
                    </Col>
                </Row>

                <Row>
                    <Col span={8}>
                        <FormItem {...formItemLayout} label={'HBL/MBL NO.'}>
                            {getFieldDecorator('mblNo')
                                (
                                <Input maxLength="20" placeholder="可根据HBL/MBL NO.搜索" style={{ width: '100%' }} />
                                )}
                        </FormItem>
                    </Col>
                    <Col span={8}>
                        <FormItem {...formItemLayout} label="提交时间">
                            {getFieldDecorator("deliveryTime")
                                (
                                <RangePicker
                                    style={{ width: "100%" }}
                                    showTime={{ format: 'YYYY-MM-DD' }}
                                    format="YYYY-MM-DD"
                                    placeholder={['开始时间', '结束时间']}
                                />
                                )}
                        </FormItem>
                    </Col>
                </Row>

                <Row>
                    <Col span={8}>
                        <FormItem {...formItemLayout} label={'起运港'}>
                            {getFieldDecorator('loadingPort')(
                                <PortSelect style={{ width: '100%' }} allowClear />
                            )}
                        </FormItem>

                    </Col>
                    <Col span={8}>
                        <FormItem {...formItemLayout} label={'目的港'}>
                            {getFieldDecorator('destinationPort')(
                                <PortSelect style={{ width: '100%' }} allowClear />
                            )}
                        </FormItem>
                    </Col>
                </Row>

                <Row>
                    <Col span={8}>
                        <FormItem {...formItemLayout} label={'客户名称'}>
                            {getFieldDecorator('cstName')
                                (
                                <Input maxLength="20" placeholder="可根据客户名称搜索" />
                                )
                            }
                        </FormItem>
                    </Col>
                    <Col span={8}>
                        <FormItem {...formItemLayout} label={'业务员'}>
                            {getFieldDecorator('ywUser')
                            (
                            <RoleSelect role={Constants.ROLE.SALES_MAN} style={{ width: '100%' }} />
                            )}
                        </FormItem>
                    </Col>
                    <Col span={7} style={{ marginLeft: 24 }}>
                        <Button type="primary" icon="search" style={{ marginRight: 5 }} onClick={this.handleSearch.bind(this, true)} size={'default'}>查询</Button>
                    </Col>
                </Row>
                <Row>
                    <Col span={8}>
                        <FormItem {...formItemLayout} label={'状态'}>
                            {getFieldDecorator('status', {
                                initialValue: ""
                            })(
                                <RadioGroup style={{width: 800}} >
                                    <Radio value="">全部</Radio>
                                    <Radio value="11">订舱中</Radio>
                                    <Radio value="2">接单</Radio>
                                    <Radio value="3">拖车</Radio>
                                    <Radio value="4">报关中</Radio>
                                    <Radio value="5">报关放行</Radio>
                                    <Radio value="6">补料</Radio>
                                    <Radio value="7">未收款</Radio>
                                    <Radio value="8">已收款</Radio>
                                    <Radio value="9">放单</Radio>
                                    <Radio value="10">上船</Radio>
                                </RadioGroup>
                        )}
                        </FormItem>
                    </Col>
                </Row>

                <Table loading={this.props.loading} rowKey='id' dataSource={this.props.order.list} columns={this.columns} bordered={true} size={'middle'} pagination={pagination}
                    title={() => <span style={{ color: 'red' }}>操作跟单列表</span>} />
                <OrderDetail wrappedComponentRef={(inst) => this.orderDetail = inst} refreshList={this.handleSearch} fetchDetail={this.fetchDetail}/>
            </div >
        );
    }
})

function mapStateToProps(state) {
    return {
        loading: state.loading.models.order, order: state.order, deliveryReceipt: state.deliveryReceipt
    };
}

export default connect(mapStateToProps)(order);
